package cn.jietuo.first.class03;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/6/21
 * @description: 求数组小和
 * 也是利用了归并排序，在merge的时候来求小和
 */
public class Code02_SmallNum {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 4, 2, 5};
        int result = process(arr, 0, arr.length - 1);
        System.out.println(result);
    }

    private static int process(int[] arr, int l, int r) {
        if (l == r) {
            return 0;
        }
        // 求mid
        int m = l + ((r - l) >> 1);
        return process(arr, l, m)
                + process(arr, m + 1, r)
                + merge(arr, l, m, r);
    }

    private static int merge(int[] arr, int l, int m, int r) {
        int[] help = new int[r - l + 1];
        int p1 = l;
        int p2 = m + 1;
        int i = 0;
        int result = 0;
        while (p1 <= m && p2 <= r) {
            result += arr[p1] < arr[p2] ? (r - p2 + 1) * arr[p1] : 0;
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        return result;
    }
}
